import React, { useState } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import {
  Layout,
  Menu,
  Button,
  Avatar,
  Dropdown,
  Typography,
  Badge,
  Space,
  Modal,
  Form,
  Input,
  message
} from 'antd';
import {
  DashboardOutlined,
  BankOutlined,
  HistoryOutlined,
  TeamOutlined,
  UserOutlined,
  WalletOutlined,
  DisconnectOutlined,
  SettingOutlined,
  MenuOutlined,
  CrownOutlined
} from '@ant-design/icons';

import { useWallet } from '../contexts/WalletContext';
import { useAuth } from '../contexts/AuthContext';
import NotificationBell from './NotificationBell';

const { Header } = Layout;
const { Text } = Typography;

const Navbar = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [passwordForm] = Form.useForm();

  const { account, networkName, isCorrectNetwork, disconnectWallet } = useWallet();
  const { user, logout } = useAuth();

  const menuItems = [
    {
      key: '/dashboard',
      icon: <DashboardOutlined />,
      label: <Link to="/dashboard">Dashboard</Link>,
    },
    {
      key: '/staking',
      icon: <BankOutlined />,
      label: <Link to="/staking">Staking</Link>,
    },
    {
      key: '/transactions',
      icon: <HistoryOutlined />,
      label: <Link to="/transactions">Transactions</Link>,
    },
    {
      key: '/referrals',
      icon: <TeamOutlined />,
      label: <Link to="/referrals">Referrals</Link>,
    },
  ];

  const handleLogout = () => {
    Modal.confirm({
      title: 'Confirm Logout',
      content: 'Are you sure you want to logout?',
      onOk: () => {
        logout();
        disconnectWallet();
        navigate('/');
      },
    });
  };

  const handleDisconnectWallet = () => {
    Modal.confirm({
      title: 'Confirm Disconnect',
      content: 'Are you sure you want to disconnect your wallet?',
      onOk: () => {
        disconnectWallet();
        navigate('/');
      },
    });
  };

  const userMenuItems = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: <Link to="/profile">Profile</Link>,
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: 'Settings',
      onClick: () => navigate('/profile'),
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <DisconnectOutlined />,
      label: 'Logout',
      onClick: handleLogout,
    },
  ];

  const formatAddress = (address) => {
    if (!address) return '';
    return `${address.slice(0, 6)}...${address.slice(-4)}`;
  };

  return (
    <>
      <Header className="fixed top-0 left-0 right-0 z-50 bg-white shadow-md px-4">
        <div className="max-w-7xl mx-auto flex items-center justify-between h-16">
          {/* Logo */}
          <div className="flex items-center space-x-4">
            <Link to="/dashboard" className="flex items-center space-x-2">
              <CrownOutlined className="text-2xl text-blue-600" />
              <span className="text-xl font-bold text-gray-900">God Token</span>
            </Link>
          </div>

          {/* Desktop Menu */}
          <div className="hidden md:block">
            <Menu
              mode="horizontal"
              selectedKeys={[location.pathname]}
              items={menuItems}
              className="border-0 bg-transparent"
            />
          </div>

          {/* Right Section */}
          <div className="flex items-center space-x-4">
            {/* Network Status */}
            <div className="hidden sm:block">
              <Badge
                status={isCorrectNetwork ? 'success' : 'error'}
                text={
                  <Text className="text-sm">
                    {networkName}
                  </Text>
                }
              />
            </div>

            {/* Notifications */}
            <NotificationBell />

            {/* Wallet Address */}
            <div className="hidden sm:flex items-center space-x-2">
              <Avatar size="small" icon={<WalletOutlined />} />
              <Text className="text-sm">{formatAddress(account)}</Text>
            </div>

            {/* User Menu */}
            <Dropdown
              menu={{ items: userMenuItems }}
              placement="bottomRight"
              trigger={['click']}
            >
              <Button type="text" icon={<UserOutlined />} className="flex items-center">
                <span className="hidden sm:inline ml-2">{user?.wallet_address?.slice(0, 6)}...</span>
              </Button>
            </Dropdown>

            {/* Mobile Menu Toggle */}
            <Button
              type="text"
              icon={<MenuOutlined />}
              className="md:hidden"
              onClick={() => setIsMobileMenuOpen(true)}
            />
          </div>
        </div>
      </Header>

      {/* Mobile Menu Drawer */}
      <Modal
        title="Menu"
        open={isMobileMenuOpen}
        onCancel={() => setIsMobileMenuOpen(false)}
        footer={null}
        className="mobile-menu-modal"
      >
        <Menu
          mode="vertical"
          selectedKeys={[location.pathname]}
          items={menuItems}
          onClick={() => setIsMobileMenuOpen(false)}
        />

        <div className="mt-6 pt-6 border-t border-gray-200">
          <div className="flex flex-col space-y-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <Avatar size="small" icon={<WalletOutlined />} />
                <Text className="text-sm">{formatAddress(account)}</Text>
              </div>
              <Badge
                status={isCorrectNetwork ? 'success' : 'error'}
                text={<Text className="text-xs">{networkName}</Text>}
              />
            </div>

            <Button
              type="primary"
              danger
              block
              icon={<DisconnectOutlined />}
              onClick={handleLogout}
            >
              Logout
            </Button>
          </div>
        </div>
      </Modal>

      {/* Password Verification Modal */}
      <Modal
        title="Verify Password"
        open={passwordModalVisible}
        onCancel={() => setPasswordModalVisible(false)}
        footer={null}
      >
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={(values) => {
            // Handle password verification
            setPasswordModalVisible(false);
            passwordForm.resetFields();
          }}
        >
          <Form.Item
            name="password"
            label="Password"
            rules={[{ required: true, message: 'Please enter your password' }]}
          >
            <Input.Password placeholder="Enter your password" />
          </Form.Item>

          <Form.Item className="mb-0">
            <Space className="w-full justify-end">
              <Button onClick={() => setPasswordModalVisible(false)}>
                Cancel
              </Button>
              <Button type="primary" htmlType="submit">
                Verify
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default Navbar;